﻿using System;
using System.Collections.Generic;

namespace Loki.Utils
{
    /// <summary>
    /// Loki services base class.
    /// </summary>
    public abstract class LokiService : LokiContextObject, IDisposable
    {
        #region IDisposable

        /// <summary>
        /// Releases all resources used by an instance of the <see cref="LokiService" /> class.
        /// </summary>
        /// <remarks>
        /// This method calls the virtual <see cref="Dispose(bool)" /> method, passing in
        /// <strong>true</strong>, and then suppresses finalization of the instance.
        /// </remarks>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~LokiService()
        {
            Dispose(false);
        }

        /// <summary>
        /// Releases the unmanaged resources used by an instance of the <see cref="LokiService" />
        /// class and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">Set to<strong>true</strong> to release both managed and
        /// unmanaged resources; <strong>false</strong> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposables != null)
            {
                foreach (var disposable in disposables)
                {
                    disposable.Dispose();
                }

                disposables.Clear();
            }
        }

        #endregion IDisposable

        #region Disposable handling

        protected void RegisterDisposable(IDisposable disposable)
        {
            disposables.Add(disposable);
        }

        private HashSet<IDisposable> disposables = new HashSet<IDisposable>();

        #endregion Disposable handling
    }
}